package tk.mybatis.springboot.controller;

import java.io.InputStream;
import java.util.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * 会员API接口
 *
 * @author admin
 */
@RequestMapping("/file")
@RestController
public class FileController {
    private static Logger logger = LoggerFactory.getLogger(FileController.class);

    private OSS ossClient;
    private String bucketName = "uniapp-mrgx";
    private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    ;
    private String accessKeyId = "LTAI5tGLXqctKUT8ryXTogk2";
    private String accessKeySecret = "HX6LqQi4pfpj6THQPQeQWXLTnGPOAu";


    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            // 初始化OSS客户端
            if (ossClient == null) {
                ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            }
            // 生成随机文件名
            String objectName = generateRandomFileName(file.getOriginalFilename());
            // 上传文件
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(new PutObjectRequest(bucketName, objectName, inputStream));
            return "https://uniapp-mrgx.oss-cn-beijing.aliyuncs.com/" + objectName;
        } catch (Exception e) {
            e.printStackTrace();
            return "Error uploading the file: " + e.getMessage();
        }
    }

    private String generateRandomFileName(String originalFileName) {
        // 生成随机字符串，并附加到原文件名后面
        String randomPart = UUID.randomUUID().toString().replaceAll("-", "");
        String fileExtension = getFileExtension(originalFileName);
        return "uploads/" + randomPart + "." + fileExtension;
    }

    private String getFileExtension(String fileName) {
        // 获取文件扩展名
        int dotIndex = fileName.lastIndexOf(".");
        return dotIndex > 0 ? fileName.substring(dotIndex + 1) : "";
    }


    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }
}